package com.jinit.rpc.consumer.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;

/**
 * 客户端处理类
 *
 * @author JInit
 * @date 2021-08-29
 */
@ChannelHandler.Sharable
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable<Object> {

    private ChannelHandlerContext context;

    /**
     * 客户端发送消息
     */
    private String requestMessage;

    /**
     * 服务端消息
     */
    private String responseMessage;

    public void setRequestMessage(String requestMsg) {
        this.requestMessage = requestMsg;
    }

    @Override
    public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        responseMessage = msg;
        notify();
    }

    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(requestMessage);
        wait();
        return responseMessage;
    }
}
